<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区 -->
      <el-row>
        <el-col>
          <el-button @click="showAddRoleDialog" type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 权限列表 -->
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 渲染一级权限 -->
            <el-row :class="['bdbottom', i1 == 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <el-col :span="5">
                <el-tag @close="removeRightById(scope.row, item1.id)" closable>
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row :class="[i2 == 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag closable @close="removeRightById(scope.row, item2.id)" type="success">
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      type="warning"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
              {{ scope.row }}
           </pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button @click="showEditRoleDialog(scope.row)" size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button @click="removeRoleById(scope.row.id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button @click="showSetRightDialog(scope.row)" size="mini" type="warning" icon="el-icon-setting">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" @close="addDialogClosed" :visible.sync="addDialogVisible" width="50%">
      <!-- 内容主体区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色对话框 -->
    <el-dialog title="修改角色" @close="editDialogClosed" :visible.sync="editDialogVisible" width="50%">
      <!-- 内容主体区 -->
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" @close="setRightDialogClosed" :visible.sync="setRightDialogVisible" width="50%">
      <!-- 内容主体区 -->
      <el-tree
        ref="rightsTreeRef"
        :data="rightsTreeData"
        :default-checked-keys="defKeys"
        node-key="id"
        show-checkbox
        default-expand-all
        :props="defaultProps"
      ></el-tree>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleList: [],
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      editForm: {
        roleName: '',
        roleDesc: ''
      },
      addFormRules: {
        roleName: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
        roleDesc: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
      },
      rightsTreeData: [],
      defKeys: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      addDialogVisible: false,
      editDialogVisible: false,
      setRightDialogVisible: false,
      currentRole: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status === 200) {
        this.roleList = res.data
      } else {
        this.$message.error('获取角色列表失败')
      }
    },
    async getRights() {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status === 200) {
        this.rightsTreeData = res.data
      } else {
        this.$message.error('获取权限数据失败')
      }
    },
    showAddRoleDialog() {
      this.addDialogVisible = true
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    addRole() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status === 201) {
          this.getRolesList()
          this.$message.success('添加角色成功')
          this.addDialogVisible = false
        } else {
          this.$message.error('添加角色失败')
        }
      })
    },
    async showEditRoleDialog(role) {
      const { data: res } = await this.$http.get(`roles/${role.id}`)

      if (res.meta.status === 200) {
        this.editForm = res.data
        this.editDialogVisible = true
      } else {
        this.$message.error('获取角色信息失败')
      }
    },
    editRole() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, this.editForm)
        if (res.meta.status === 200) {
          this.getRolesList()
          this.$message.success('修改角色成功')
          this.editDialogVisible = false
        } else {
          this.$message.error('修改角色失败')
        }
      })
    },

    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    async removeRoleById(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((e) => e)

      if (confirmResult === 'cancel') {
        return this.$message.info('取消了删除操作')
      } else {
        const { data: res } = await this.$http.delete(`roles/${id}`)
        if (res.meta.status === 200) {
          this.$message.success('删除成功')
          this.getRolesList()
        } else {
          this.$message.error(res.meta.msg)
        }
      }
    },
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirmResult === 'cancel') {
        return this.$message.info('取消了删除操作')
      } else {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (res.meta.status === 200) {
          this.$message.success('删除成功')
          // this.getRolesList()
          role.children = res.data
        } else {
          this.$message.error(res.meta.msg)
        }
      }
    },
    showSetRightDialog(role) {
      this.defKeys = []
      this.currentRole = role
      this.getDefKeys(role, this.defKeys)
      this.getRights()
      this.setRightDialogVisible = true
    },
    getDefKeys(node, arr) {
      if (!node.children) {
        arr.push(node.id)
      } else {
        node.children.forEach((item) => {
          this.getDefKeys(item, arr)
        })
      }
    },
    setRightDialogClosed() {},
    async setRight() {
      var rids = [...this.$refs.rightsTreeRef.getCheckedKeys(), ...this.$refs.rightsTreeRef.getHalfCheckedKeys()].join(',')
      const { data: res } = await this.$http.post(`roles/${this.currentRole.id}/rights`, { rids: rids })
      if (res.meta.status === 200) {
        this.setRightDialogVisible = false
        this.getRolesList()
        this.$message.success('分配权限成功')
      } else {
        this.$message.error('分配权限失败')
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>